package com.zhuliwei.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.domain.entity.Sentence;
import com.zhuliwei.enums.AppHttpCodeEnum;
import com.zhuliwei.service.SentenceService;
import com.zhuliwei.utils.WebUtils;
import io.swagger.annotations.Api;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 句子控制层
 *
 * @author zlw
 * @date 2023/5/25
 */
@RestController
@RequestMapping("/content/sentence")
@Api(tags="句子",description = "句子相关接口")
public class SentenceController {
    @Resource
    private SentenceService sentenceService;

    /**
     * 句子列表
     *
     * @return list
     */
    @GetMapping("/list")
    @PreAuthorize("@ps.hasPermission('content:sentence:list')")
    public ResponseResult<Sentence> getSentences(Integer pageNum, Integer pageSize, Sentence sentence){
        return sentenceService.getSentences(pageNum,pageSize,sentence);
    }

    @PostMapping
    @PreAuthorize("@ps.hasPermission('content:sentence:add')")
    public ResponseResult addSentence(@RequestBody Sentence sentence) {
        return sentenceService.addSentence(sentence);
    }

    @DeleteMapping("/{ids}")
    @PreAuthorize("@ps.hasPermission('content:sentence:delete')")
    public ResponseResult delSentence(@PathVariable List<String> ids) {
        return sentenceService.delSentence(ids);
    }

    @GetMapping("/{id}")
    public ResponseResult sentenceDetail(@PathVariable String id) {
        Sentence sentence = sentenceService.getById(id);
        return ResponseResult.okResult(sentence);
    }

    @PutMapping
    @PreAuthorize("@ps.hasPermission('content:sentence:update')")
    public ResponseResult updateSentence(@RequestBody Sentence sentence) {
        return sentenceService.updateSentence(sentence);
    }

    @GetMapping("/export")
    @PreAuthorize("@ps.hasPermission('content:sentence:export')")
    public void export(HttpServletResponse response){
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("句子库.xlsx",response);
            //获取需要导出的数据
            List<Sentence> sentences = sentenceService.list();
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), Sentence.class).autoCloseStream(Boolean.FALSE).sheet("句子库导出")
                    .doWrite(sentences);

        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }
}
